import { _decorator, Component, ImageAsset, Node, Sprite, SpriteFrame, tween, UIOpacity, EventTarget, Vec3, Prefab, instantiate } from 'cc';
import { fadeOut, fitCover, Logger } from 'db://assets/util';
import { ResourceLoad, ServiceLocator } from '../service';
import { Chapter } from 'db://assets/store';
import { STATE, TIMER } from 'db://assets/enum';
const { ccclass, property, menu } = _decorator;

@ccclass('FGPFrame')
@menu('frame/FGP')
export class FGPFrame extends Component {
    #logger = new Logger('前景容器::FGPFrame')
    #resourceLoader = new ResourceLoad()
    #service = ServiceLocator;

    @property(Prefab)
    fgpNode: Prefab

    get chapter() {
        return this.#service.get<Chapter>(STATE.CHAPTER)
    }

    protected onLoad(): void {
        this.#logger.debug('#onLoad')
    }

    start() {
        this.#logger.debug('#start')
    }

    async clear(): Promise<void> {
        if (this.node.active) {
            for (const node of this.node.children) {
                await fadeOut(node, TIMER.FAST)
            }
        }
    }

    async showFGP(resourceId: number): Promise<Node> {
        this.#logger.debug('#showFGP %s', resourceId)
        const resourceUrl = this.chapter.getResource(resourceId)
        const image = await this.#resourceLoader.loadRemote<ImageAsset>(resourceUrl.ossUrl)
        const sp = SpriteFrame.createWithImage(image)
        const node = instantiate(this.fgpNode)
        node.getComponent(Sprite).spriteFrame = sp
        this.node.addChild(node)
        fitCover(image, node)
        return node
    }

    async transformFrame(content: LDContent.TransformContent) {
        return new Promise(resolve => tween(this.node)
            .to(content.duration, {
                scale: new Vec3(content.scale, content.scale, 0),
                position: new Vec3(-content.scale * content.x, content.scale * content.y, 0),
            }, { easing: content.easing })
            .call(resolve)
            .start())
    }
}
